package com.hl.mystudy.ui.home.ui.viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.PagerAdapter;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hl.mystudy.R;
import com.hl.mystudy.bean.User;
import com.hl.mystudy.databinding.ActivityViewPagerLoadDataBinding;
import com.hl.mystudy.databinding.ItemVpLoadDataBinding;
import com.hl.mystudy.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerLoadDataActivity extends AppCompatActivity {

    private ActivityViewPagerLoadDataBinding mBinding;
    private ViewPagerLoadDataViewModel mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_view_pager_load_data);
        mViewModel = new ViewModelProvider(this).get(ViewPagerLoadDataViewModel.class);
        mViewModel.getUserListLive().observe(this, users -> {
            LogUtil.i("数据变换了");
        });
        mBinding.vpLoadData.setAdapter(new MyDataAdapter(mViewModel.getTestData()));
    }

    private class MyDataAdapter extends PagerAdapter {
        LayoutInflater inflater;
        ItemVpLoadDataBinding binding;

        List<User> dataList = new ArrayList<>(16);

        public MyDataAdapter(List<User> testData) {
            inflater = LayoutInflater.from(ViewPagerLoadDataActivity.this);
            dataList = testData;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return ((ItemVpLoadDataBinding) object).getRoot() == view;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            binding = DataBindingUtil.inflate(inflater, R.layout.item_vp_load_data, container, true);
            User user = dataList.get(position);
            binding.tvName.setText("姓名:" + user.getName());
            binding.tvAge.setText("性别:" + user.getAge());
            binding.tvSex.setText("年龄:" + user.getSex());
            return binding;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView(((ItemVpLoadDataBinding) object).getRoot());
        }
    }
}